﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Cost.Models;
using NBlock.Core;
using NBlock.Components.Excel;
using NBlock.MVCExtensions;
using Cost.Services;

namespace Cost.Controllers
{
    public class MaterialPriceController : Controller
    {
        #region 构造函数
        private readonly ICostRepository<MaterialPrice> materialPriceRepository;
        private readonly IEnumService enumService;
        private readonly IExcelImporter excelImporter;
        private readonly MaterialService materialService;
        public MaterialPriceController(ICostRepository<MaterialPrice> materialPriceRepository,
            IEnumService enumService,
            IExcelImporter excelImporter,
            MaterialService materialService)
        {
            this.materialPriceRepository = materialPriceRepository;
            this.enumService = enumService;
            this.excelImporter = excelImporter;
            this.materialService = materialService;
        }
        #endregion

        public ActionResult Index()
        {
            ViewBag.Date = DateTime.Now.ToString("yyyy-MM-dd");
            return View();
        }

        public ActionResult Edit(string Id)
        {
            var data = materialPriceRepository.Find(Id);
            if (data == null)
            {
                data = new MaterialPrice();
                var day = DateTime.Now.Day;
                var lastday = DateTime.DaysInMonth(DateTime.Now.Year, DateTime.Now.Month);
                if (day <= 15)
                {
                    data.StartDate = DateTime.Now.AddDays(-day + 1);
                    data.EndDate = DateTime.Now.AddDays(-day + 15);
                }
                else
                {
                    data.StartDate = DateTime.Now.AddDays(-day + 16);
                    data.EndDate = DateTime.Now.AddDays(-day + lastday);
                }
            }
            return View(data);
        }

        [HttpPost]
        public JsonResult Save(string Id)
        {
            var data = materialPriceRepository.Find(Id) ?? new MaterialPrice();
            TryUpdateModel(data);
            data.MaterialName = enumService.GetEnumText("Material", data.MaterialId);
            data.SupplierName = enumService.GetEnumText("Supplier", data.SupplierId);
            materialPriceRepository.Save(data);
            return Json(nbAjaxMessage.Successful);
        }

        [HttpPost]
        public JsonResult Delete(string Id)
        {
            materialPriceRepository.Delete(Id);
            return Json(nbAjaxMessage.Successful);
        }

        [HttpPost]
        public JsonResult DeleteAll(string Ids)
        {
            var items = Ids.Split(',');
            materialPriceRepository.DeleteAll(d => items.Contains(d.Id));
            return Json(nbAjaxMessage.Successful);
        }

        [HttpPost]
        public JsonResult List(string datetime, nbPageInfo pager, nbSearchCondition where)
        {
            var pageData = materialPriceRepository.GetPageable(pager, where);
            if (!string.IsNullOrEmpty(datetime))
            {
                var date = Convert.ToDateTime(datetime);
                pageData = materialPriceRepository.GetPageable(pager, m => m.StartDate <= date && m.EndDate >= date, where);
            }

            var data = pager.ToGridData(pageData);
            return Json(data);
        }

        /// <summary>
        /// 获取上期价格
        /// </summary>
        /// <param name="MaterialId"></param>
        /// <param name="SupplierId"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult GetPrePrice(string MaterialId)
        {
            decimal price = 0;
            if (!string.IsNullOrEmpty(MaterialId))
            {
                var date = materialPriceRepository.FindAll(m => m.MaterialId == MaterialId).OrderByDescending(m => m.EndDate).FirstOrDefault();
                if (date != null)
                    price = date.Price;
            }
            return Json(nbAjaxMessage.Successful.SetData(price));
        }

        #region 数据导入
        public ActionResult Import(string excelKey)
        {
            ViewBag.TemplateUrl = excelImporter.GetExcelTemplateUrl(excelKey);
            ViewBag.ExcelKey = excelKey;
            return View();
        }

        [HttpPost]
        public nbFileUploadJsonResult Import(HttpPostedFileBase file, string ExcelKey, string UpdateMode)
        {
            try
            {
                // 保留导入文档，以便后续检查
                var path = Server.MapPath("~/Upload/") + System.IO.Path.GetFileName(file.FileName).Replace(".", "_" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".");
                file.SaveAs(path);

            }
            catch (Exception ex)
            {
                // TODO 记录日志
            }

            var notMaterial = "";
            var data = excelImporter.Import(file, ExcelKey);
            foreach (var row in data.RepeatData.Rows)
            {
                var item = row.ToEntity<MaterialPrice>();
                var oldItem = materialPriceRepository.Find(m => m.SupplierName == item.SupplierName
                    && m.MaterialName == item.MaterialName
                    && m.StartDate == item.StartDate
                    && m.EndDate == item.EndDate);
                if (oldItem != null)
                {
                    item = row.ToEntity(oldItem);
                }
                else
                {
                    item.SupplierId = enumService.GetEnumValue("Supplier", item.SupplierName);
                    if (string.IsNullOrWhiteSpace(item.SupplierId))
                    {
                        // Todo 提示用户
                        continue;
                    }

                    var material = materialService.GetMaterial(m => m.Name == item.MaterialName);
                    if (material != null)
                    {
                        item.MaterialId = material.Id;
                        item.Specification = material.Specification;
                        item.Unit = material.Unit;
                        item.Category = material.Category;
                    }
                    else
                    {
                        // Todo 提示用户，找不到指定品名名称的品名
                        notMaterial += "," + item.MaterialName;
                        continue;
                    }
                }
                materialPriceRepository.Save(item);
            }
            return new nbFileUploadJsonResult { Data = nbAjaxMessage.Successful };
        }

        #endregion
    }
}
